package com.rinlink.gateway.jt808.controller;

import com.google.common.collect.Maps;
import com.rinlink.gateway.jt808.common.CommonResult;
import com.rinlink.gateway.jt808.common.CommonStatusCode;
import com.rinlink.gateway.jt808.exception.HttpApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.LinkedHashMap;

@ControllerAdvice
@Slf4j
public class ExceptionController {

    @ExceptionHandler(Throwable.class)
    public ResponseEntity unknownError(Throwable err){
        log.warn("未知异常",err);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
                CommonResult.of(CommonStatusCode.UNKNOWN_ERROR)
        );
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity MethodArgumentNotValidException(MethodArgumentNotValidException ex){
        FieldError fieldError = ex.getBindingResult().getFieldError();
        String msg = fieldError.getDefaultMessage();
        String field = fieldError.getField();
        msg = String.format("%s %s",field,msg);
        CommonResult result = CommonResult.of(CommonStatusCode.INVALID_PARAM,msg,new LinkedHashMap<>());
        return ResponseEntity.badRequest().body(result);
    }

    @ExceptionHandler(HttpApiException.class)
    public ResponseEntity httpApiException(HttpApiException e){
        log.warn("HttpApiException",e);
        CommonResult result = CommonResult.of(e.getStatusCode(),e.getMessage(), Maps.newHashMap());
        return ResponseEntity.status(e.getHttpStatus()).body(result);
    }


}
